package com.wolfcode.web.controller.common;

import com.wolfcode.common.annotation.Log;
import com.wolfcode.common.enums.BusinessType;
import com.wolfcode.common.utils.StringUtils;
import com.wolfcode.common.utils.file.FileUploadUtils;
import com.wolfcode.common.utils.uuid.IdUtils;
import com.wolfcode.goods.domain.Goods;
import com.wolfcode.goods.domain.vo.GoodsVo;
import com.wolfcode.goods.mapper.GoodsMapper;
import io.minio.BucketExistsArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.errors.*;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.List;

@RestController
public class GoodsCoverController {
    @Autowired
    private GoodsMapper goodsMapper;

    /**
     * MinIO上传请求
     */
    @PostMapping("/goods/goods")
    @ResponseBody
    public void minIoUploadFile(GoodsVo goodsVo) throws Exception {
        //参数校验
        Assert.notNull(goodsVo, "参数异常");
        Assert.notNull(goodsVo.getGoodsName(),"名称不能为空");
        Assert.notNull(goodsVo.getGoodsCover(),"图片不能为空");
        //todo 联调时打开
        Assert.notNull(goodsVo.getBusiPath(),"分类不能为空");
        String busiPath = null;
        if (goodsVo.getBusiPath() != null) {
            List<String> busiPaths= goodsVo.getBusiPath();
            busiPath = busiPaths.get(busiPaths.size() - 1);
        }
        String url = upload(goodsVo.getGoodsCover());
        Goods goods = new Goods();
        BeanUtils.copyProperties(goodsVo, goods);
        goods.setGoodsCover(url);
        goods.setCategoryId(busiPath);
        goodsMapper.insertGoods(goods);
    }

    /**
     * 修改物品信息
     */
    @PreAuthorize("@ss.hasPermi('goods:goods:edit')")
    @Log(title = "物品信息", businessType = BusinessType.UPDATE)
    @PutMapping("/goods/goods")
    public void edit( GoodsVo goodsVo) throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, NoSuchAlgorithmException, ServerException, InternalException, XmlParserException, ErrorResponseException {
        //参数校验
        Assert.notNull(goodsVo, "参数异常");
        Assert.notNull(goodsVo.getGoodsName(),"名称不能为空");
        Assert.notNull(goodsVo.getGoodsCover(),"图片不能为空");
        //todo 联调时打开
        //Assert.notNull(goodsVo.getBusiPath(),"分类不能为空");
        String busiPath = null;
        if (goodsVo.getBusiPath() != null) {
            List<String> busiPaths = goodsVo.getBusiPath();
            busiPath = busiPaths.get(busiPaths.size() - 1);
        }
        String url = upload(goodsVo.getGoodsCover());
        Goods goods = new Goods();
        BeanUtils.copyProperties(goodsVo,goods);
        goods.setCategoryId(busiPath);
        goods.setGoodsCover(url);
        goodsMapper.updateGoods(goods);
    }

    @NotNull
    private String upload(MultipartFile file) throws IOException, ErrorResponseException, InsufficientDataException, InternalException, InvalidKeyException, InvalidResponseException, NoSuchAlgorithmException, ServerException, XmlParserException {
        // 主机地址, 即我们要存放的服务器目标地址
        String endpoint = "http://xue.cnkdl.cn:23900";
        // 账号
        String accessKey = "developer";
        // 密码
        String secretKey = "wolfcode.cn";
        // 存储空间, 即我们要存放的目录
        String bucket = "car";
        // 自己生成唯一的文件名
        String fileName = IdUtils.fastSimpleUUID() + System.currentTimeMillis();
        // 获取文件后缀
        String extension = FileUploadUtils.getExtension(file);
        InputStream inputStream = file.getInputStream();

        if (StringUtils.isNotEmpty(extension)) {
            fileName = fileName.concat(".").concat(extension);
        }
        // 使用步骤：
        // 1：创建minio客户端连接对象
        MinioClient minioClient = MinioClient.builder().endpoint(endpoint).credentials(accessKey, secretKey).build();
        // 2: 检查存储空间是否存在, 存储空间不存在上传不了
        boolean exists = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucket).build());
        Assert.notNull(exists,"存储空间不存在!");


        PutObjectArgs objectArgs = PutObjectArgs.builder()
                .bucket(bucket)
                .object(fileName)
                .stream(inputStream, inputStream.available(), -1)
                .build();

        // 3:上传文件
        minioClient.putObject(objectArgs);
        //4：拼接图片访问连接
        String url = endpoint + "/" + bucket + "/" + fileName;

        return url;
    }
}
